package dao

import (
	"go-admin/global"
	"go-admin/internal/model"
	mr "go-admin/internal/model/api/model_request"
	_const "go-admin/internal/model/const"
	"go-admin/pkg/app"
	"time"
)

// 创建字典项
func (d *Dao) CreateDictItem(param *mr.CreateDictItemRequest) (string, error) {
	dictItem := model.DictItem{
		CommonModel: model.CommonModel{
			Id:    global.GetId(),
			IsDel: _const.ISDEL,
		},
		DictType: param.DictType,
		DictId:   param.DictId,
		Label:    param.Label,
		Value:    param.Value,
		IsBanned: _const.ISBANNED,
		Sort:     param.Sort,
	}
	return dictItem.Create(d.Engine)
}

// 查询总数
func (d *Dao) CountDictItem(param *mr.ListDictItemRequest) (int, error) {
	dictItem := model.DictItem{
		IsBanned: param.IsBanned,
		Label:    param.Label,
		DictType: param.DictType,
	}
	return dictItem.Count(d.Engine)
}

// 获取字典项列表
func (d *Dao) GetDictListItem(param *mr.ListDictItemRequest, pageIndex, pageSize int) ([]*model.DictItem, error) {
	dictItem := model.DictItem{
		IsBanned: param.IsBanned,
		Label:    param.Label,
		DictType: param.DictType,
	}
	pageOffset := app.GetPageOffset(pageIndex, pageSize)
	return dictItem.List(d.Engine, pageOffset, pageSize)
}

func (d *Dao) UpdateDictItem(param *mr.UpdateDictItemRequest) error {
	dictItem := model.DictItem{
		CommonModel: model.CommonModel{
			Id: param.Id,
		},
	}
	values := map[string]interface{}{
		"is_banned":   param.IsBanned,
		"modified_on": time.Now().Local().Unix(),
		"sort":        param.Sort,
	}
	if param.Remark != "" {
		values["remark"] = param.Remark
	}
	return dictItem.Update(d.Engine, values)
}

// 根据字典类型判断是否存在重复的字典项
func (d *Dao) GetDictByDictItemLabelAndValueByDictType(label, value, dictType string) (*model.DictItem, error) {
	dictItem := model.DictItem{
		DictType: dictType,
		Label:    label,
		Value:    value,
	}
	return dictItem.GetDictByDictItemLabelAndValueByDictType(d.Engine)
}

// 根据id获取详情
func (d *Dao) GetDictItemById(Id string) (*model.DictItem, error) {
	dictItem := model.DictItem{
		CommonModel: model.CommonModel{Id: Id},
	}
	return dictItem.GetDictItemById(d.Engine)
}

func (d *Dao) DeleteDictItemS(ids []string) error {
	dictItem := model.DictItem{}
	values := map[string]interface{}{
		"deleted_on": time.Now().Local().Unix(),
		"is_del":     _const.DEL,
	}
	return dictItem.Deletes(d.Engine, ids, values)
}

func (d *Dao) DictItemList(dictType string) ([]*model.DictItem, error) {
	dictItem := model.DictItem{}
	return dictItem.DictItemList(d.Engine, dictType)
}
